<?php
class UserController extends MA_Controller_Action
{
	public function applicationsAction()
	{
		
		$query = $this->_adapter->select() 
			->from( array( 'u' => 'users') )
			->join(	array( 'ua' => 'user_applications'), 'ua.user_id = u.user_id' )
			->join(	array( 'a' => 'applications'), 'a.application_id = ua.application_id') 
			->where( 'u.user_id = ?', $this->_user->userId )
			->where( 'a.status = 1' );  
		$this->view->applications = $this->_adapter->fetchAll( $query );
	}
	public function loginAction()
	{
		if( $this->_user->userId != 0 ){
			$this->_redirect( '/user/profile/');		
		}
		/**
		 * 1- Chequear si la cookie existe. 
		 * 2t- Si existe la cookie chequear que el usuario este logueado en alguna aplicacion
		 * 3t- Fijarse de que aplicacion viene y chequear si esta habilitado
		 * 4t- Si lo esta redirecciono a la aplicacion, dandole permiso en la bd. 
		 * 5- Si la cookie no existe la creo, con un token. Ese token, voy a pasarlo por parametro
		 * 6- Valido los datos con los que se registra el usuario. y voy al paso 3  
		 */
		$loginForm = new MA_Forms_Login();
        if ( $this->_request->isPost() ) {
            $credentials = $this->_request->getPost();
            if ( $loginForm->isValid( $credentials )) {
            	$usersModel = new Users();
				$userData = $usersModel->isValid( $credentials['username'], $credentials['password'] );
          		if( $userData === false ){
					$this->_flashMessenger->addError( MA_Error_User::getInstance()->get('USER_DATA_UNKNOW' ));
                	$loginForm->populate( $credentials );
				} elseif ( $userData instanceof MA_Error_User ) {
					$this->_flashMessenger->addError( $userData );
					$loginForm->populate( $credentials );
				} else {
					$service = (isset ($_GET['service'] ) ) ? $_GET['service'] : null;
	            	$loginResponse = $this->_user->login( $credentials['username'], $credentials['password'], $service );
	            	if ( $loginResponse instanceof MA_Error_User) {
	            		$this->_flashMessenger->addError( $loginResponse );
	            	} elseif ( is_array( $loginResponse )) {
	            		$this->_redirect( $loginResponse );
	            	} elseif ( $loginResponse === true ){
	            		$this->_redirect( '/user/profile' );
	            	} else {
	                	$this->_flashMessenger->addError( MA_Error_User::getInstance()->get('USER_DATA_PROBLEM') );
	                	$loginForm->populate( $credentials );
	                }
				}
			} else {
                $this->_flashMessenger->addError( MA_Error_User::getInstance()->get('USER_DATA_PROBLEM') );
                $loginForm->populate( $credentials );
            }
        }
        $this->view->loginForm = $loginForm; 	    	
	}
	public function logoutAction ()
	{
		if( $this->_user->userId == 0 ){
			$this->_redirect( '/user/login/');		
		}
		$statusModel = new StatusUserLogin();
		//$this->_user->userId = 0;
		$row = $statusModel->find( $this->_user->token )->current();
		if ( count ($row)) {
			$row->user_id = 0;
			$row->login_date = NULL;
			$row->save();
			$this->_user->userId = 0;
			$this->_user->loginDate = NULL;
		} 
		$this->_redirect('/user/login/');
	}
	public function registerAction()
	{
		if( $this->_user->userId != 0 ){
			$this->_redirect( '/user/profile/');		
		}
		$registerForm = new MA_Forms_Register();
        if ( $this->_request->isPost() ) {
            $userData = $this->_request->getPost();
            if ( $registerForm->isValid( $userData )) {
				$message = $this->_user->register(	$userData);
			} else {
				$message = MA_Apis_UserError::getInstance()->get( 'USER_DATA_PROBLEM');
            }
            if( is_string( $message ) ) {
            	$this->_flashMessenger->addError( $message );
            	$registerForm->populate( $userData );
            } else {
            	$this->_redirect( '/user/active/' );
            }
        }
        $this->view->registerForm = $registerForm; 	    	
		
	}
	public function activeAction()
	{
		if( $this->_user->userId != 0 ){
			$this->_redirect( '/user/profile/');		
		}
		if ( $this->_request->getParam('token')) {
			$this->view->checkMail = false;
			if( $this->_user->activate( $this->_request->getParam('token') ))	{
				$this->_flashMessenger->addError( MA_Apis_UserError::getInstance()->get( 'ACTIVE_USER') );
			} else {
				$this->_flashMessenger->addError( MA_Apis_UserError::getInstance()->get( 'NO_ACTIVE_USER') );
			} 
		} else {
			$this->_user->confirmAccount();
			$this->view->checkMail = true;	
		}
	}
	public function resetPasswordAction()
	{
		if( $this->_user->userId != 0 ){
			$this->_redirect( '/user/profile/');		
		}
		$resetPasswordForm = new MA_Forms_ResetPassword();
        if ( $this->_request->isPost() ) {
            $userData = $this->_request->getPost();
            if ( $resetPasswordForm->isValid( $userData )) {
            	echo "Validar y guardar datos";
			} else {
                $this->_flashMessenger->addError( MA_Apis_UserError::USER_DATA_PROBLEM );
                $resetPasswordForm->populate( $userData );
            }
        }
        $this->view->resetPasswordForm = $resetPasswordForm; 	    	
	}
	public function profileAction()
	{
		if( $this->_user->userId == 0 ){
			$this->_redirect( '/user/login/');		
		}
		$user = $this->_user->getProfile();
		$profileForm = new MA_Forms_Profile();
        if ( $this->_request->isPost() ) {
            $userData = $this->_request->getPost();
            if ( $profileForm->isValid( $userData )) {
				$message = $this->_user->update( $userData );
				$message = 'ANDA';
			} else {
				$message = MA_Apis_UserError::getInstance()->get( 'USER_DATA_PROBLEM');
            }
           	$this->_flashMessenger->addError( $message );
           	$profileForm->populate( $userData );
        } else {
        	$profileForm->populate( $user );
        }
        $this->view->profileForm = $profileForm; 	    	
	}
}